const httpRequest = require('../../utils/request');
const buildUrl = httpRequest.buildUrl || ((url) => url);
Page({
  data: {
    // 筛选条件
    timeRange: 'week',
    startDate: '',
    endDate: '',
    dataTypeFilter: 'all',
    comparePeriod: 'last_week',
    showFilterModal: false,

    // 绩效数据
    performanceStats: {
      totalIncome: 0,
      weekIncome: 0,
      monthIncome: 0,
      quarterIncome: 0,
      yearIncome: 0,

      completedOrders: 0,
      avgRating: 0,
      completionRate: 0,
      avgDeliveryTime: 0,
      totalOrders: 0,
      cancelledOrders: 0,
      timeoutOrders: 0,
      avgAcceptTime: 0,
      fastestDelivery: 0,
      slowestDelivery: 0,
      avgOrderIncome: 0,
      maxOrderIncome: 0,
      minOrderIncome: 0,
      dailyAvgIncome: 0
    },

    // 趋势数据
    incomeTrend: 0,
    orderTrend: 0,
    ratingTrend: 0,
    completionTrend: 0,
    timeTrend: 0,

    // 当前展示收入（随 timeRange 切换）
    currentIncome: 0,

    // 图表数据
    chartData: {
      period: '本周',
      points: []
    },

    // 收入趋势折线图画布尺寸
    canvasWidth: 0,
    canvasHeight: 0,

    // 评分分布
    ratingDistribution: [],

    // 绩效建议
    suggestions: []
  },

  onLoad() {
    this.initDates();

    const sys = wx.getSystemInfoSync();
    const width = sys.windowWidth - 80; // 考虑左右边距
    this.setData({
      canvasWidth: width,
      canvasHeight: 160
    });

    this.loadPerformanceData();
  },

  onShow() {
    this.refreshPerformanceData();
  },

  // 初始化日期
  initDates() {
    const today = new Date();
    const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

    this.setData({
      startDate: this.formatDate(oneWeekAgo),
      endDate: this.formatDate(today)
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 获取当前月份的天数，用于计算日均收入
  getDaysInCurrentMonth() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth(); // 0-11
    // 下月1号减一天，就是本月最后一天
    const lastDay = new Date(year, month + 1, 0);
    return lastDay.getDate();
  },

  // 加载绩效数据
  async loadPerformanceData() {
    try {
      const userId = wx.getStorageSync('userId');
      if (!userId) return;

      // 基本绩效指标来自 /api/couriers/performance/:userId
      const perfRes = await httpRequest({
        url: `/api/couriers/performance/${userId}`,
        method: 'GET'
      });

      console.log('📈 绩效数据响应:', perfRes);

      if (perfRes.success && perfRes.data) {
        const p = perfRes.data;
        const daysInMonth = this.getDaysInCurrentMonth();

        const performanceStats = {
          totalOrders: p.totalOrders || 0,
          completedOrders: p.completedOrders || 0,
          avgRating: p.avgRating || 0,
          completionRate: p.completionRate || 0,
          totalIncome: p.totalIncome || 0,
          weekIncome: p.weekIncome || 0,
          monthIncome: p.monthIncome || 0,
          quarterIncome: p.quarterIncome || 0,
          yearIncome: p.yearIncome || 0,
          avgDeliveryTime: p.avgDeliveryTime || 0,
          cancelledOrders: p.cancelledOrders || 0,
          timeoutOrders: p.timeoutOrders || 0,
          avgAcceptTime: p.avgAcceptTime || 0,
          fastestDelivery: p.fastestDelivery || 0,
          slowestDelivery: p.slowestDelivery || 0,
          avgOrderIncome: p.avgOrderIncome || 0,
          maxOrderIncome: p.maxOrderIncome || 0,
          minOrderIncome: p.minOrderIncome || 0,
          // 日均收入：按当前月份的自然日来算
          dailyAvgIncome: daysInMonth > 0 ? (p.monthIncome || 0) / daysInMonth : 0
        };

        this.setData({
          performanceStats,
          currentIncome: this.getCurrentIncomeByRange(performanceStats),
          loadingPerformanceData: false
        });

        // 根据最新数据生成绩效建议
        this.generateSuggestions();
      }

      // 收入趋势从订单列表中按日聚合，根据当前 timeRange 生成折线
      await this.loadIncomeTrendFromOrders(userId);
    } catch (err) {
      console.error('加载绩效数据失败:', err);
      this.setData({
        loadingPerformanceData: false
      });
    }
  },

  // 从 /api/orders/courier/:userId 聚合收入，生成折线图数据
  async loadIncomeTrendFromOrders(userId) {
    try {
      const res = await httpRequest({
        url: `/api/orders/courier/${userId}`,
        method: 'GET'
      });

      let orders = [];
      if (res.success && res.data) {
        if (Array.isArray(res.data)) {
          orders = res.data;
        } else if (Array.isArray(res.data.orders)) {
          orders = res.data.orders;
        }
      }

      const now = new Date();

      // 根据当前 timeRange 决定统计区间
      let start;
      let end = now;
      const range = this.data.timeRange;

      if (range === 'month') {
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29); // 近30天
      } else if (range === 'quarter') {
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 89); // 近90天
      } else if (range === 'year') {
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 364); // 近1年
      } else if (range === 'custom' && this.data.startDate && this.data.endDate) {
        // 自定义时间段：使用用户选择的起止日期
        start = new Date(this.data.startDate + 'T00:00:00');
        end = new Date(this.data.endDate + 'T23:59:59');
      } else {
        // 默认使用最近7天
        start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6);
      }

      // 构造区间内每天的 key
      const oneDayMs = 24 * 60 * 60 * 1000;
      const dailyMap = {};
      const dayCount = Math.floor((end.setHours(0, 0, 0, 0) - start.setHours(0, 0, 0, 0)) / oneDayMs) + 1;
      for (let i = 0; i < dayCount; i++) {
        const d = new Date(start.getTime() + i * oneDayMs);
        const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
        dailyMap[key] = 0;
      }

      orders.forEach(o => {
        // 只统计已完成订单，status = 5
        if (o.status !== 5) return;

        const t = o.completed_at || o.delivered_at || o.created_at;
        if (!t) return;

        const d = new Date(t);
        const key = `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
        if (Object.prototype.hasOwnProperty.call(dailyMap, key)) {
          const amount = Number(o.final_fee || o.suggested_fee || o.amount || 0) || 0;

          dailyMap[key] += amount;
        }
      });

      const labels = ['一', '二', '三', '四', '五', '六', '日'];
      const rawPoints = Object.keys(dailyMap).sort().map((day, idx) => ({
        label: `周${labels[idx]}`,
        value: Number(dailyMap[day].toFixed(2))
      }));

      console.log('📊 rawPoints from orders:', rawPoints);

      const processed = this.processChartData(rawPoints);

      console.log('📊 processed chart points length:', processed.length);

      this.setData({
        chartData: {
          period: this.getChartPeriodText(),
          points: processed
        }
      });

      console.log('📊 chartData set in state:', this.data.chartData);

      this.drawIncomeChart();
    } catch (e) {
      console.error('加载收入趋势失败:', e);
    }
  },

  // 加载图表数据
  async loadChartData() {
    const app = getApp();
    const userId = app.globalData.userId;

    try {
      const res = await this.request({
        url: `/api/courier-users/performance/chart`,
        method: 'GET',
        data: {
          userId: userId,
          timeRange: this.data.timeRange,
          startDate: this.data.startDate,
          endDate: this.data.endDate
        }
      });

      if (res.success) {
        this.setData({
          chartData: {
            period: this.getChartPeriodText(),
            points: this.processChartData(res.data)
          }
        });

        this.drawIncomeChart();
      }
    } catch (error) {
      console.error('加载图表数据失败:', error);
    }
  },

  // 处理图表数据
  processChartData(data) {
    const maxValue = Math.max(...data.map(item => item.value));
    const minValue = Math.min(...data.map(item => item.value));
    const valueRange = maxValue - minValue || 1;

    return data.map((item, index) => {
      const valuePosition = ((item.value - minValue) / valueRange) * 80 + 10; // 10% - 90%
      const position = (index / (data.length - 1)) * 100;

      return {
        label: item.label,
        value: item.value,
        valuePosition,
        position
      };
    });
  },
  // 在 canvas 上绘制收入折线图
  drawIncomeChart() {
    const points = this.data.chartData.points || [];
    const width = this.data.canvasWidth || 300;
    const height = this.data.canvasHeight || 160;

    console.log('📈 drawIncomeChart called, points:', points, 'canvas size:', width, height);

    if (!points.length) return;

    // 调整留白，让折线区域整体更靠上
    const paddingLeft = 32;
    const paddingRight = 24;
    const paddingTop = 18;
    const paddingBottom = 90;

    const ctx = wx.createCanvasContext('incomeCanvas', this);

    ctx.clearRect(0, 0, width, height);

    // 坐标轴范围
    const maxValue = Math.max(...points.map(p => p.value));
    const minValue = Math.min(...points.map(p => p.value));
    const range = maxValue - minValue || 1;

    const usableWidth = width - paddingLeft - paddingRight;
    const usableHeight = height - paddingTop - paddingBottom;

    const axisY = height - paddingBottom; // 横轴 y 坐标

    // 绘制横轴
    ctx.setStrokeStyle('#e5e7eb');
    ctx.setLineWidth(1);
    ctx.beginPath();
    ctx.moveTo(paddingLeft, axisY);
    ctx.lineTo(width - paddingRight, axisY);
    ctx.stroke();

    // 绘制纵轴
    ctx.beginPath();
    ctx.moveTo(paddingLeft, paddingTop - 4);
    ctx.lineTo(paddingLeft, axisY);
    ctx.stroke();

    // 计算各点坐标
    const coords = points.map((p, idx) => {
      const x = paddingLeft + (points.length === 1 ? usableWidth / 2 : (usableWidth * idx) / (points.length - 1));
      const y = paddingTop + usableHeight * (1 - (p.value - minValue) / range);
      return { x, y, value: p.value };
    });

    // 绘制折线
    ctx.setStrokeStyle('#2563eb');
    ctx.setLineWidth(2);
    ctx.beginPath();
    coords.forEach((c, idx) => {
      if (idx === 0) {
        ctx.moveTo(c.x, c.y);
      } else {
        ctx.lineTo(c.x, c.y);
      }
    });
    ctx.stroke();

    // 绘制数据点
    ctx.setFillStyle('#2563eb');
    coords.forEach(c => {
      ctx.beginPath();
      ctx.arc(c.x, c.y, 3, 0, 2 * Math.PI);
      ctx.fill();
    });

    // 绘制横坐标标签（周一、周二等）
    ctx.setFillStyle('#9ca3af');
    ctx.setFontSize(10);
    points.forEach((p, idx) => {
      const x = paddingLeft + (points.length === 1 ? usableWidth / 2 : (usableWidth * idx) / (points.length - 1));
      ctx.fillText(p.label, x - 12, axisY + 14);
    });

    // 绘制纵坐标刻度线和文字（最小值、中间值、最大值）
    const yTicks = [minValue, minValue + range / 2, maxValue];
    yTicks.forEach(val => {
      const ratio = (val - minValue) / range;
      const y = paddingTop + usableHeight * (1 - ratio);

      // 刻度文字
      ctx.setFillStyle('#d1d5db');
      ctx.setFontSize(9);
      ctx.fillText(String(val.toFixed(0)), 4, y + 3);

      // 水平辅助线
      ctx.setStrokeStyle('#f3f4f6');
      ctx.setLineWidth(1);
      ctx.beginPath();
      ctx.moveTo(paddingLeft, y);
      ctx.lineTo(width - paddingRight, y);
      ctx.stroke();
    });

    ctx.draw();
  },

  // 生成绩效建议
  generateSuggestions() {
    const { performanceStats } = this.data;
    const suggestions = [];
    const totalIncome = Number(performanceStats.totalIncome || 0);
    const weekIncome = Number(performanceStats.weekIncome || 0);
    const completedOrders = Number(performanceStats.completedOrders || 0);
    const completionRate = Number(performanceStats.completionRate || 0);
    const avgOrderIncome = completedOrders > 0 ? totalIncome / completedOrders : 0;

    // 收入建议：结合平均单价和本周收入
    if (avgOrderIncome < 3 || weekIncome < 10) {
      suggestions.push({
        type: 'income',
        icon: '💰',
        title: '提升订单收入',
        level: 'urgent',
        levelText: '急需改善',
        content: '您的最近收入表现偏低，建议多接高价订单或在高峰时段增加接单量.',
        tip: '优先选择距离适中、报酬较高的订单，可以明显提升收入'
      });
    } else if (avgOrderIncome < 6 || weekIncome < 30) {
      suggestions.push({
        type: 'income',
        icon: '💰',
        title: '优化收入结构',
        level: 'warning',
        levelText: '建议优化',
        content: '您的收入表现良好，但仍有提升空间，可以适当筛选更高价的订单.',
        tip: '保持高评分有助于获得更多优质订单和小费'
      });
    } else {
      suggestions.push({
        type: 'income',
        icon: '💰',
        title: '收入表现优秀',
        level: 'good',
        levelText: '表现优秀',
        content: '您的收入水平表现优秀，说明您的接单策略和服务质量都很好.',
        tip: '可以在保证服务质量的前提下，逐步提高每日接单量'
      });
    }

    // 评分建议
    if (performanceStats.avgRating < 4.0) {
      suggestions.push({
        type: 'rating',
        icon: '⭐',
        title: '提升服务评分',
        level: 'urgent',
        levelText: '急需改善',
        content: '您的服务评分较低，建议改进服务态度和配送时效.',
        tip: '及时沟通和礼貌服务能显著提升用户满意度'
      });
    } else if (performanceStats.avgRating < 4.5) {
      suggestions.push({
        type: 'rating',
        icon: '⭐',
        title: '优化服务体验',
        level: 'warning',
        levelText: '建议优化',
        content: '您的服务评分良好，但仍有提升空间，关注用户反馈.',
        tip: '主动询问用户需求可以提升服务体验'
      });
    } else {
      suggestions.push({
        type: 'rating',
        icon: '⭐',
        title: '服务评价优秀',
        level: 'good',
        levelText: '表现优秀',
        content: '您的服务评分非常优秀，用户满意度很高！',
        tip: '继续保持优质服务，您将获得更多订单'
      });
    }

    // 效率建议（根据平均配送时间）
    if (performanceStats.avgDeliveryTime > 30) {
      suggestions.push({
        type: 'efficiency',
        icon: '⏱️',
        title: '提升配送效率',
        level: 'urgent',
        levelText: '急需改善',
        content: '您的平均配送时间较长，建议优化路线规划或提升配送速度.',
        tip: '提前规划路线，避开拥堵时段'
      });
    } else if (performanceStats.avgDeliveryTime > 20) {
      suggestions.push({
        type: 'efficiency',
        icon: '⏱️',
        title: '优化配送流程',
        level: 'warning',
        levelText: '建议优化',
        content: '您的配送效率良好，但仍有优化空间.',
        tip: '熟悉校园路线可以显著提升配送速度'
      });
    } else {
      suggestions.push({
        type: 'efficiency',
        icon: '⏱️',
        title: '配送效率优秀',
        level: 'good',
        levelText: '表现优秀',
        content: '您的配送速度非常优秀，用户很满意！',
        tip: '继续保持高效配送，您将获得更多好评'
      });
    }

    // 结合完成率补充建议
    if (completionRate < 60 && completedOrders >= 5) {
      suggestions.push({
        type: 'completion',
        icon: '🎯',
        title: '提升订单完成率',
        level: 'urgent',
        levelText: '急需改善',
        content: '您的订单完成率偏低，建议合理安排接单数量，避免超出自己的配送能力.',
        tip: '优先保证已接订单按时完成，再考虑增加接单量'
      });
    } else if (completionRate < 80) {
      suggestions.push({
        type: 'completion',
        icon: '🎯',
        title: '优化接单策略',
        level: 'warning',
        levelText: '建议优化',
        content: '可以适当减少路线过长或时间过紧的订单，保证每一单都能顺利完成.',
        tip: '接单前先粗略估算配送时间，避免同时接太多远距离订单'
      });
    }

    this.setData({ suggestions });
  },

  // 获取图表周期文本
  getChartPeriodText() {
    const periodMap = {
      week: '本周',
      month: '本月',
      quarter: '本季',
      year: '今年',
      custom: '自定义'
    };
    return periodMap[this.data.timeRange] || '本周';
  },

  // 根据当前时间范围获取对应收入
  getCurrentIncomeByRange(performanceStats) {
    const range = this.data.timeRange;
    if (range === 'week') return Number(performanceStats.weekIncome || 0);
    if (range === 'month') return Number(performanceStats.monthIncome || 0);
    if (range === 'quarter') return Number(performanceStats.quarterIncome || 0);
    if (range === 'year') return Number(performanceStats.yearIncome || 0);
    // 自定义时段默认展示总收入
    return Number(performanceStats.totalIncome || 0);
  },

  // 获取时间范围文本
  get timeRangeText() {
    const rangeMap = {
      week: '本周',
      month: '本月',
      quarter: '本季度',
      year: '本年度',
      custom: '自定义时段'
    };
    return rangeMap[this.data.timeRange] || '本周';
  },

  // 设置时间范围
  setTimeRange(e) {
    const range = e.currentTarget.dataset.range;
    this.setData({
      timeRange: range,
      currentIncome: this.getCurrentIncomeByRange(this.data.performanceStats)
    });
    this.refreshPerformanceData();
  },

  // 显示自定义日期选择
  showCustomDatePicker() {
    this.setData({ timeRange: 'custom' });
  },

  // 日期变化
  onStartDateChange(e) {
    this.setData({ startDate: e.detail.value });
  },

  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
  },

  // 应用自定义日期
  applyCustomDate() {
    this.refreshPerformanceData();
  },

  // 显示筛选模态框
  showFilterModal() {
    this.setData({ showFilterModal: true });
  },

  hideFilterModal() {
    this.setData({ showFilterModal: false });
  },

  // 设置数据类型筛选
  setDataTypeFilter(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ dataTypeFilter: type });
  },

  // 设置对比周期
  setComparePeriod(e) {
    const period = e.currentTarget.dataset.period;
    this.setData({ comparePeriod: period });
  },

  // 重置筛选
  resetFilters() {
    this.setData({
      dataTypeFilter: 'all',
      comparePeriod: 'last_week'
    });
  },

  // 应用筛选
  applyFilters() {
    this.hideFilterModal();
    this.refreshPerformanceData();
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 刷新绩效数据
  refreshPerformanceData() {
    this.loadPerformanceData();
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshPerformanceData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});